using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesMyDraft : System.Web.UI.Page
{
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;

    #region ResultTable
    protected DataTable ResultTable {
        
        get
        {
            return (DataTable)ViewState[GonzalesCommonNamingConvention.CurrentPrivateSessionViewState];
        }

        set
        {
            ViewState[GonzalesCommonNamingConvention.CurrentPrivateSessionViewState] = value;
        }
    }
    #endregion 

    #region Common Variables for Language Translation
    protected string DeleteConfirmation
    {
        get
        {
            return ViewState["DeleteConfirmation"].ToString();
        }

        set
        {
            ViewState["DeleteConfirmation"] = value;
        }
    }

    protected string ItemDate
    {
        get
        {
            return ViewState["ItemDate"].ToString();
        }

        set
        {
            ViewState["ItemDate"] = value;
        }
    }

    protected string ItemCategory
    {
        get
        {
            return ViewState["ItemCategory"].ToString();
        }

        set
        {
            ViewState["ItemCategory"] = value;
        }
    }

    protected string ItemPurpose
    {
        get
        {
            return ViewState["ItemPurpose"].ToString();
        }

        set
        {
            ViewState["ItemPurpose"] = value;
        }
    }

    protected string ItemClaimPeriod
    {
        get
        {
            return ViewState["ItemClaimPeriod"].ToString();
        }

        set
        {
            ViewState["ItemClaimPeriod"] = value;
        }
    }

    protected string ItemAmount
    {
        get
        {
            return ViewState["ItemAmount"].ToString();
        }

        set
        {
            ViewState["ItemAmount"] = value;
        }
    }

    protected string SortByASC
    {
        get
        {
            return ViewState["SortByASC"].ToString();
        }

        set
        {
            ViewState["SortByASC"] = value;
        }
    }

    protected string SortByDESC
    {
        get
        {
            return ViewState["SortByDESC"].ToString();
        }

        set
        {
            ViewState["SortByDESC"] = value;
        }
    }

    protected string LinkDelete
    {
        get
        {
            return ViewState["LinkDelete"].ToString();
        }

        set
        {
            ViewState["LinkDelete"] = value;
        }
    }

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();
        this.DetectDeletion();

        if (!IsPostBack)
        {
            this.SwitchLanguage();
            this.PageComponentSetup();

            this.LoadData();

            if (this.ResultTable != null)
            {
                DataView ResultView = new DataView(this.ResultTable);
                ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                this.BindData(ResultView);
            }
        }        
    }
    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataView ResultView = new DataView(this.ResultTable);
        ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
        this.BindData(ResultView);
    }
    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortOrder_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataView ResultView = new DataView(this.ResultTable);
        ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
        this.BindData(ResultView);
    }

    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {

    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");

                this.DeleteConfirmation = CurLanguageFactory.DisplayValue("DeleteConfirmation");
                this.ItemAmount = CurLanguageFactory.DisplayValue("ItemAmount");
                this.ItemDate = CurLanguageFactory.DisplayValue("ItemDateCreated");
                this.ItemPurpose = CurLanguageFactory.DisplayValue("ItemPurpose");
                this.ItemClaimPeriod = CurLanguageFactory.DisplayValue("ItemClaimPeriod");
                this.ItemCategory = CurLanguageFactory.DisplayValue("ItemCategory");
                this.LinkDelete = CurLanguageFactory.DisplayValue("ItemDelete");

                // sort order
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("SortOrderASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("SortOrderDESC"), "DESC"));

                // sort by
                this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemDate, "DateCreated"));
                this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemCategory, "Category"));
                this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemPurpose, "Purpose"));
                this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemClaimPeriod, "ClaimPeriod"));
                this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemAmount, "Amount"));

                // GridView
                this.GridViewResult.Columns[0].HeaderText = this.ItemDate;
                this.GridViewResult.Columns[1].HeaderText = this.ItemCategory;
                this.GridViewResult.Columns[2].HeaderText = this.ItemPurpose;
                this.GridViewResult.Columns[3].HeaderText = this.ItemClaimPeriod;
                this.GridViewResult.Columns[4].HeaderText = this.ItemAmount;
                
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMyDraft.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #endregion

    #region Data Operation

    protected void LoadData()
    {
        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            ClaimHeaders ResultObj = CurClaimManager.GetClaimByStatus(GonzalesClaimHeader.TypeOfClaimStatus.Draft, this.CurrentPrivateSession.CurrentLoggedOnUser);

            if (ResultObj != null)
            {
                this.ResultTable = new DataTable();
                ResultTable.Columns.Add(new DataColumn("DateCreated", Type.GetType("System.DateTime")));
                ResultTable.Columns.Add(new DataColumn("DateCreatedInString", Type.GetType("System.String")));
                ResultTable.Columns.Add(new DataColumn("Category", Type.GetType("System.String")));
                ResultTable.Columns.Add(new DataColumn("Purpose", Type.GetType("System.String")));
                ResultTable.Columns.Add(new DataColumn("Amount", Type.GetType("System.Decimal")));
                ResultTable.Columns.Add(new DataColumn("AmountInStr", Type.GetType("System.String")));
                ResultTable.Columns.Add(new DataColumn("ClaimPeriod", Type.GetType("System.String")));
                ResultTable.Columns.Add(new DataColumn("DeleteLink", Type.GetType("System.String")));

                DataRow RowObj = null;

                for (int x = 0; x < ResultObj.Count; x++)
                {
                    RowObj = ResultTable.NewRow();

                    GonzalesClaimHeader CurClaimHeader = (GonzalesClaimHeader)ResultObj[x];

                    RowObj["DateCreated"] = ResultObj[x].CreatedOn;
                    RowObj["DateCreatedInString"] = "<a href='GonzalesMyDraftDetail.aspx?id=" + ResultObj[x].InternalID + "' class='GridViewLink'>" + SwissArmy.DateConvert(ResultObj[x].CreatedOn, this.CurrentPrivateSession.DateFormatInUse, "/") + "</a>";
                    RowObj["Category"] = ClaimManager.GetClaimCategoryInString(CurClaimHeader.Category);
                    RowObj["Purpose"] = ResultObj[x].Reasons;
                    RowObj["Amount"] = ResultObj[x].TotalClaimedAmount;
                    RowObj["AmountInStr"] = ResultObj[x].TotalClaimedAmount.ToString(GonzalesGeneralVariables.CurrencyFormat);
                    if (ResultObj[x].ProjectedOn != DateTime.MinValue)
                        RowObj["ClaimPeriod"] = ResultObj[x].ProjectedOn.Year.ToString() + " - " + ResultObj[x].ProjectedOn.Month.ToString();//ResultObj[x].ProjectedOn.ToString("MMMM") + " " + ResultObj[x].ProjectedOn.Year.ToString();
                    else
                        RowObj["ClaimPeriod"] = "";
                    RowObj["DeleteLink"] = "<a href='GonzalesMyDraft.aspx?id=" + ResultObj[x].InternalID + "&DELETE=1' onclick='return confirm(\"" + DeleteConfirmation + "\");' class='GridViewLink'>" + this.LinkDelete + "</a>";

                    ResultTable.Rows.Add(RowObj);
                }

            }
            else
            {
                this.CurLogManager.LogError("[GonzalesMyDraft.LoadData] : Failed at CurClaimManager.GetClaimByStatus() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }
    }

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    protected void DetectDeletion()
    {
        if (Request.QueryString["DELETE"] != null && 
            Request.QueryString["DELETE"].CompareTo("1") == 0 &&
            Request.QueryString["id"].Length == 36)
        {
            bool smooth = true;            

            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                if (!(smooth = CurClaimManager.DeleteClaimByClaimant(Request.QueryString["id"])))
                {
                    // log error
                    this.CurLogManager.LogError("[GonzalesMyDraft.DetectDeletion] : Failed at CurClaimManager.DeleteClaimByClaimant('" + Request.QueryString["id"] + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
                else
                {
                    // clear credit card items, if any
                    using (CreditCardManager CurCreditCardManager = new CreditCardManager(this.CurrentPrivateSession))
                    {
                        if (!(smooth = CurCreditCardManager.ClearCreditCardItems(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID)))
                        {
                            // log error
                            this.CurLogManager.LogError("[GonzalesMyDraft.DetectDeletion] : Failed at CurCreditCardManager.ClearCreditCardItems('" + this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        }
                        
                    }
                }
                
            }

            string PageRedirect = (smooth) ? "GonzalesMyDraft.aspx" : "";
            Response.Redirect(PageRedirect);
            
        }
    }

    #endregion


}
